package com.aikon.wht.concurrent;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author haitao.wang http://www.bestwonderful.com
 */
public class TestOfCondition {

    static volatile int i = 1;

    public static void main(String[] args) {
        Lock lock = new ReentrantLock();
        Condition condition1 = lock.newCondition();
        Condition condition2 = lock.newCondition();
        for (int j=0;j<10;j++) {
            new Thread(new ConditionThread(lock,condition1,i),"Thread"+i).start();
        }


    }

    public static class ConditionThread implements Runnable{
        public Lock lock;
        public Condition condition;
        int i;

        public ConditionThread(Lock lock,Condition condition) {
            this.lock = lock;
            this.condition = condition;
        }

        public ConditionThread(Lock lock, Condition condition, int i) {
            this.lock = lock;
            this.condition = condition;
            this.i = i;
        }

        @Override
        public void run() {
            try {
                lock.lock();
                while (i != 1) {
                    condition.await();
                }
                System.out.println(Thread.currentThread().getName() + " begin");
                condition.signalAll();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();

            }
        }
    }
}
